using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using PatentAssistant.Services;
using PatentAssistant.Utils;

namespace PatentAssistant
{
    /// <summary>
    /// AIConfigDialog.xaml 的交互逻辑
    /// </summary>
    public partial class AIConfigDialog : Window, INotifyPropertyChanged
    {
        #region 属性

        private string _apiUrl = "http://192.168.100.71:8000/v1/chat/completions";
        public string ApiUrl
        {
            get => _apiUrl;
            set
            {
                _apiUrl = value;
                OnPropertyChanged();
            }
        }

        private string _modelName = "deepseek-r1-70b";
        public string ModelName
        {
            get => _modelName;
            set
            {
                _modelName = value;
                OnPropertyChanged();
            }
        }

        private double _temperature = 0.7;
        public double Temperature
        {
            get => _temperature;
            set
            {
                _temperature = value;
                OnPropertyChanged();
            }
        }

        private bool _isConnected = false;
        public bool IsConnected
        {
            get => _isConnected;
            set
            {
                _isConnected = value;
                OnPropertyChanged();
                OnPropertyChanged(nameof(ConnectionStatus));
                OnPropertyChanged(nameof(ConnectionColor));
            }
        }

        public string ConnectionStatus => IsConnected ? "已连接" : "未连接";
        public Brush ConnectionColor => IsConnected ? Brushes.Green : Brushes.Red;

        #endregion

        #region 命令

        public ICommand TestConnectionCommand { get; }

        #endregion

        private readonly AIService _aiService;

        public AIConfigDialog(AIService aiService)
        {
            InitializeComponent();
            _aiService = aiService;
            
            // 初始化命令
            TestConnectionCommand = new RelayCommand(async _ => await TestConnection(), _ => !string.IsNullOrEmpty(ApiUrl));
            
            DataContext = this;
            
            // 加载当前配置
            LoadCurrentConfig();
        }

        /// <summary>
        /// 加载当前配置
        /// </summary>
        private void LoadCurrentConfig()
        {
            // 这里可以从配置文件或AIService中加载当前配置
            // 暂时使用默认值
        }

        /// <summary>
        /// 测试连接
        /// </summary>
        private async Task TestConnection()
        {
            try
            {
                // 创建临时AIService进行测试
                var tempService = new AIService(ApiUrl, ModelName);
                var result = await tempService.CallAIAsync("测试连接", "test_connection");
                
                if (!result.Contains("API调用出错"))
                {
                    IsConnected = true;
                    MessageBox.Show("连接测试成功！", "连接测试", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    IsConnected = false;
                    MessageBox.Show("连接测试失败！", "连接测试", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
            catch (Exception ex)
            {
                IsConnected = false;
                MessageBox.Show($"连接测试出错: {ex.Message}", "连接测试", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(ApiUrl))
            {
                MessageBox.Show("请输入API地址！", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (string.IsNullOrWhiteSpace(ModelName))
            {
                MessageBox.Show("请输入模型名称！", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            // 更新AIService配置
            _aiService.UpdateConfig(ApiUrl, ModelName, Temperature);
            
            DialogResult = true;
            Close();
        }

        /// <summary>
        /// 取消配置
        /// </summary>
        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }

        #region INotifyPropertyChanged

        public event PropertyChangedEventHandler? PropertyChanged;

        protected void OnPropertyChanged([CallerMemberName] string? name = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }

        #endregion
    }
} 